package org.intellij.plugins.junit4;

import javax.swing.*;
import java.awt.*;

/**
 * Displays the configuration GUI in IDEA.
 *
 * @author Justin Tomich
 */
@SuppressWarnings({"RedundantIfStatement"})
public class ConfigurationPanel extends JPanel
{
    private JTextField prefix;
    private JTextField suffix;


    public ConfigurationPanel()
    {
        setLayout(new BorderLayout());
        add(createTestClassNamePanel(), BorderLayout.CENTER);
    }


    public String getPrefix()
    {
        return prefix.getText();
    }


    public String getSuffix()
    {
        return suffix.getText();
    }


    public void setTo(Configuration conf)
    {
        conf.setPrefix(prefix.getText());
        conf.setSuffix(suffix.getText());
    }


    public void readFrom(Configuration conf)
    {
        prefix.setText(conf.getPrefix());
        suffix.setText(conf.getSuffix());
    }


    public boolean isModified(Configuration conf)
    {
        if (prefix.getText() != null ?
                !prefix.getText().equals(conf.getPrefix()) :
                conf.getPrefix() != null)
        {
            return true;
        }

        if (suffix.getText() != null ?
                !suffix.getText().equals(conf.getSuffix()) :
                conf.getSuffix() != null)
        {
            return true;
        }

        return false;
    }


    private Component createTestClassNamePanel()
    {
        JPanel panel = new JPanel(new FlowLayout(FlowLayout.LEFT));
        Box nameBox = Box.createVerticalBox();
        prefix = new JTextField(20);
        suffix = new JTextField(20);

        nameBox.setBorder(BorderFactory.createTitledBorder("Test Class Naming"));
        nameBox.add(createTextEntry(prefix, "Test class name prefix."));
        nameBox.add(Box.createVerticalStrut(10));
        nameBox.add(createTextEntry(suffix, "Test class name suffix."));
        nameBox.add(Box.createVerticalGlue());
        panel.add(nameBox);
        return panel;
    }


    private Component createTextEntry(JTextField widget, String instructions)
    {
        Box nameWidget = createLeftAlignedBox(widget);
        Box instructionsBox = createLeftAlignedBox(new JLabel(instructions));
        Box box = Box.createVerticalBox();
        box.add(nameWidget);
        box.add(instructionsBox);
        return box;
    }


    private Box createLeftAlignedBox(JComponent comp)
    {
        Box box = Box.createHorizontalBox();
        box.add(comp);
        box.add(Box.createHorizontalGlue());
        return box;
    }
}
